package com.xcc.wavzmp3;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.zrgg.futuwen.R;
import com.zrgg.futuwen.Urltool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.finalteam.galleryfinal.GalleryFinal;

/**
 * Created by kalunren on 2017/6/12.
 * 20180311
 * 修复横竖屏问题
 * 20180403
 修复摄像头预览变形,保存变形
 */

public class CaptureActivity extends AppCompatActivity implements View.OnClickListener {
    Camera camera;
    SurfaceView surfaceView;
    int facing = Camera.CameraInfo.CAMERA_FACING_BACK, cameraId;

    RelativeLayout rlStart, rlDecide;
    byte[] data;
    MediaRecorder mMediaRecorder;
    String videoPath;
    // 相机支持的尺寸
    Point bestSize;
    MediaPlayer mediaplayer;
    View viewBig, viewSmall;
    long start;
    RingProgress ringProgress;

    // 控制最大录制长度
    CountDownHandler countDownHandler;

    Handler handler = new Handler();
    Runnable captureVideo = new Runnable() {
        @Override
        public void run() {
            Log.e(CaptureActivity.class.getSimpleName(), "开始算为长按，开始拍视频");
            enlarge();
            prepareVideoRecorder();
            countDownHandler.start();
        }
    };



    private int mRotationRecord=90;//视频输出角度 0横屏  90竖屏  180反横屏
    private boolean isRecording;//正在录制


    //存储路径,默认配置好了
    String destnationPath;

    //最多只能录视频的时间长度
    int maxDuration;

    //图片,视频,所有
    int type;


    final int 开始录制识别时间 = 500;

    final int 最短录制时间 = 3000;


    MSCMode mscMode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mscMode = (MSCMode) getIntent().getSerializableExtra(getClass().getSimpleName());

        Urltool.log(mscMode.toString());


        type = mscMode.optInt("type");

        //默认的视频时长
        maxDuration = mscMode.optInt("maxDuration");

        destnationPath = getIntent().getStringExtra("destnationPath");

        if (Urltool.isEmpty(destnationPath)) {
            //默认的存储路径
            destnationPath = ZRFileTool.getAppCacheFile();
        }


        initUi();


        //手机旋转监听
        OrientationEventListener orientationEventListener=new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                //录制的过程不改变
                if(isRecording){
                    return;
                }

//                if (((rotation >= 0) && (rotation <= 30)) || (rotation >= 330)) {
//                    // 竖屏拍摄
//                    mRotationRecord=90;
//                } else if (((rotation >= 230) && (rotation <= 310))) {
//                    // 横屏拍摄
//                    mRotationRecord=0;
//                } else if (rotation > 30 && rotation < 95) {
//                    // 反横屏拍摄
//                    mRotationRecord=180;
//                }


//只检测是否有四个角度的改变
                if (rotation > 350 || rotation < 10) { //0度
                    mRotationRecord = 90;
                } else if (rotation > 80 && rotation < 100) { //90度
                    mRotationRecord = 180;
                } else if (rotation > 170 && rotation < 190) { //180度
                    mRotationRecord = 270;
                } else if (rotation > 260 && rotation < 280) { //270度
                    mRotationRecord = 0;
                }


            }
        };
        orientationEventListener.enable();
    }


    TextView capture_toast;
    private void initUi() {
        WindowManager.LayoutParams winParams = getWindow().getAttributes();
        winParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        winParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        getWindow().setAttributes(winParams);

        setContentView(R.layout.activity_capture);
        surfaceView = (SurfaceView) findViewById(R.id.surface_capture);
        surfaceView.setFocusableInTouchMode(true);
        surfaceView.setSecure(true);
        rlDecide = (RelativeLayout) findViewById(R.id.rl_decide);
        rlStart = (RelativeLayout) findViewById(R.id.rl_start);
        viewSmall = findViewById(R.id.view_small);
        viewBig = findViewById(R.id.view_big);
        ringProgress = (RingProgress) findViewById(R.id.ring_progress);


        capture_toast = (TextView) findViewById(R.id.capture_toast);


        switch (type) {

            case 1:
                capture_toast.setText("点击拍照");


                rlStart.setOnClickListener(this);


                break;

            case 2:
                capture_toast.setText("长按录像");

                rlStart.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("录像", event.getAction() + "");
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                isRecording = true;
                                start = System.currentTimeMillis();
                                handler.post(captureVideo);
                                break;
                            case MotionEvent.ACTION_CANCEL:
                            case MotionEvent.ACTION_UP:

                                // 控制最短录制时间
                                long gap = System.currentTimeMillis() - start;
                                int delay = gap > 最短录制时间 ? 0 : (int) (最短录制时间 - gap);
                                countDownHandler.stop();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mMediaRecorder != null) {
                                            isRecording = false;
                                            recover();
                                            stopRecord();
                                        }
                                    }
                                }, delay);
                                break;
                        }

                        return true;
                    }
                });

                break;

            case 3:
                capture_toast.setText("点击拍照,长按录像");


                rlStart.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("拍摄", event.getAction() + "");
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                isRecording = true;
                                start = System.currentTimeMillis();
                                handler.postDelayed(captureVideo, 开始录制识别时间);
                                break;
                            case MotionEvent.ACTION_CANCEL:
                            case MotionEvent.ACTION_UP:
                                isRecording = false;
                                handler.removeCallbacks(captureVideo);
                                long gap = System.currentTimeMillis() - start;
                                if (gap > 开始录制识别时间) {
                                    countDownHandler.stop();
                                    //录像
                                    int delay = gap > 最短录制时间 ? 0 : (int) (最短录制时间 - gap);

                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            recover();
                                            stopRecord();
                                        }
                                    }, delay);

                                } else {
                                    recover();
                                    //拍照
                                    takePicture();
                                }

                                break;
                        }

                        return true;
                    }
                });


                break;


        }


        countDownHandler = new CountDownHandler(ringProgress, maxDuration, new Runnable() {
            @Override
            public void run() {
                MotionEvent simulateUpEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
                dispatchTouchEvent(simulateUpEvent);//最大时间限制到了，模拟用户松开手指
            }
        });
        findViewById(R.id.iv_cancel).setOnClickListener(this);
        findViewById(R.id.iv_ok).setOnClickListener(this);

        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (camera != null)
                    camera.autoFocus(new Camera.AutoFocusCallback() {
                        @Override
                        public void onAutoFocus(boolean success, Camera camera) {


                        }
                    });
            }
        });

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//                if (holder.getSurface() == null)
//                    return;


//                surfaceView.getHolder().setFixedSize(width, height);
//                surfaceView.requestLayout();
//                surfaceView.invalidate();



            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // 保持屏幕常亮
                holder.setKeepScreenOn(true);

//                holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                startPreview(-1);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                stopPreview();
            }
        });

        checkPermission();
    }

    // 申请权限
    private void checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        String[] permissions = {
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        ArrayList<String> needRequestPermission = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (checkSelfPermission(permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermission.add(permissions[i]);
            }
        }
        if (!needRequestPermission.isEmpty()) {
            requestPermissions(needRequestPermission.toArray(new String[needRequestPermission.size()]), 11);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        startPreview(-1);
    }

    public void startPreview(int _cameraId) {
        if (_cameraId == -1) {
            int numberOfCameras = Camera.getNumberOfCameras();
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int i = 0; i < numberOfCameras; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    facing = cameraInfo.facing;
                    cameraId = i;
                    break;
                }
            }
        } else
            cameraId = _cameraId;
        try {
            camera = Camera.open(cameraId);
            camera.setDisplayOrientation(90);
            camera.setPreviewDisplay(surfaceView.getHolder());
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            Camera.Parameters parameters = camera.getParameters();


            Point bestPreviewSize = getBestCameraResolution(parameters, false);
            parameters.setPreviewSize(bestPreviewSize.x, bestPreviewSize.y);
            float y = bestPreviewSize.y;//720
            float x = bestPreviewSize.x;//1280
            float y1 = Urltool.getWindow_width();
            float x1 = (x * y1) / y;
            surfaceView.setLayoutParams(new RelativeLayout.LayoutParams((int) y1, (int) x1));
            Urltool.log(bestPreviewSize.x + ":" + bestPreviewSize.y + ":bestPreviewSize");


            Point bestPictureSize = getBestCameraResolution(parameters, true);
            parameters.setPictureSize(bestPictureSize.x, bestPictureSize.y);
            Urltool.log(bestPictureSize.x + ":" + bestPictureSize.y + ":bestPictureSize");


            // 这里选取真正支持录制的尺寸去保存照片,视频用系统的录制
            bestSize = bestPictureSize;
            Urltool.log(bestSize.x + ":" + bestSize.y + ":bestSize");


            camera.setParameters(parameters);
            camera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
            if(camera!=null){
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }
        if (camera == null) {
            new AlertDialog.Builder(CaptureActivity.this)
                    .setTitle("提示")
                    .setCancelable(false)
                    .setMessage("无法获取摄像头数据，请在手机应用权限管理中打开摄像头权限。")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create().show();
            return;
        }
    }

    public void stopPreview() {
        if (camera == null)
            return;
        camera.stopPreview();
        camera.setPreviewCallback(null);
        camera.release();
        camera = null;
    }

    /**
     * 切换摄像头
     *
     * @param view
     */
    public void switchCamera(View view) {
        int numberOfCameras = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing != facing) {
                stopPreview();
                startPreview(i);
                facing = cameraInfo.facing;
                cameraId = i;
                break;
            }
        }
    }

    private Point getBestCameraResolution(Camera.Parameters parameters, boolean isPicture) {
        Camera.Size best = null;

        List<Camera.Size> sizeList;
        if (isPicture) {
            // 相机支持的尺寸
            sizeList = parameters.getSupportedPictureSizes();
        } else {
            //获取预览的各种分辨率
            sizeList = parameters.getSupportedPreviewSizes();
        }

        // 按符合屏幕比例的排序
        Collections.sort(sizeList, new Comparator<Camera.Size>() {
            @Override
            public int compare(Camera.Size o1, Camera.Size o2) {
                Float bili = getbili(o1);
                Float bili2 = getbili(o2);
                return bili.compareTo(bili2);
            }

            private float getbili(Camera.Size size) {
                float x = size.width;
                float y = size.height;
                //相机是横着的
                float x1 = Urltool.getWindow_hith();
                float y1 = Urltool.getWindow_width();
                return Math.abs(((x / y) - (x1 / y1)));
            }
        });


        for (int i = 0; i < sizeList.size(); i++) {
            Camera.Size s = sizeList.get(i);
            Urltool.log(s.width + ":" + s.height + isPicture + "i" + i);
        }

//        for (int i = 0; i < sizeList.size(); i++) {
//            Camera.Size s = sizeList.get(i);
//
//            if (s.width == 640)
//                return new Point(s.width, s.height);
//
//            if (s.width == 720)
//                return new Point(s.width, s.height);
//
//            if (best == null) {
//                best = s;
//            }
//        }

//        // 取最接近屏幕的
        best = sizeList.get(0);



        return new Point(best.width, best.height);
    }

    private void enlarge() {
        ObjectAnimator smallScaleXAnimator = ObjectAnimator.ofFloat(viewSmall, "scaleX", 0.5f);
        ObjectAnimator smallScaleYAnimator = ObjectAnimator.ofFloat(viewSmall, "scaleY", 0.5f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(smallScaleXAnimator, smallScaleYAnimator);
        animatorSet.setDuration(400);
        animatorSet.start();

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewBig.getLayoutParams();
        layoutParams.height = getResources().getDimensionPixelSize(R.dimen.circle_large_size);
        layoutParams.width = layoutParams.height;
        viewBig.setLayoutParams(layoutParams);
    }

    private void recover() {
        ObjectAnimator smallScaleXAnimator = ObjectAnimator.ofFloat(viewSmall, "scaleX", 1);
        ObjectAnimator smallScaleYAnimator = ObjectAnimator.ofFloat(viewSmall, "scaleY", 1);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(smallScaleXAnimator, smallScaleYAnimator);
        animatorSet.setDuration(getResources().getInteger(R.integer.anim_duration));
        animatorSet.start();

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewBig.getLayoutParams();
        layoutParams.height = getResources().getDimensionPixelSize(R.dimen.circle_normal_size);
        layoutParams.width = layoutParams.height;
        viewBig.setLayoutParams(layoutParams);
    }


    private void clearVideoFile() {
        if (videoPath == null)
            return;
        File file = new File(videoPath);
        if (file.exists())
            file.delete();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止录制视频
        justStopRecord();

        showStart();
        stopVideo();
    }

    @Override
    public void finish() {
        super.finish();
        captureVideo = null;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_start) {
            takePicture();
        } else if (v.getId() == R.id.iv_cancel) {
            showStart();
            stopVideo();
            startPreview(cameraId);

            clearVideoFile();
        } else if (v.getId() == R.id.iv_ok) {
            if (data != null)
                savePictureAsync();
            else
                saveVideo();
        }
    }

    // 拍照
    private void takePicture() {
        if (camera == null)
            return;
        try {
            camera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    CaptureActivity.this.data = data;
                    stopPreview();
                    showDecide();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveVideo() {
        int duration = mediaplayer != null ? mediaplayer.getDuration() : 0;
        stopVideo();
//        Photo photo = new Photo();
//        photo.isapp = true;
//        photo.setWidth(bestSize.x);
//        photo.setHeight(bestSize.y);
//        photo.setFullImage(false);
//        photo.setMimetype("video/mp4");
//        photo.setPath(videoPath);
//        photo.setSize(new File(videoPath).length());
//        photo.setDuration(duration);
//        send(photo);
        finish();
    }

//    private void send(Photo photo) {
//        if (GalleryFinal.mOnSelectMediaListener != null) {
//            ArrayList<Photo> list = new ArrayList<>();
//            list.add(photo);
//            GalleryFinal.mOnSelectMediaListener.onSelected(list);
//        }
//
////        EventBus.getDefault().post(photo);
//    }

    private void showStart() {
        rlDecide.setVisibility(View.GONE);
        rlStart.setVisibility(View.VISIBLE);
        findViewById(R.id.iv_switch).setVisibility(View.VISIBLE);
    }

    public void showDecide() {
        rlDecide.setVisibility(View.VISIBLE);
        rlStart.setVisibility(View.GONE);
        findViewById(R.id.iv_switch).setVisibility(View.GONE);
    }

    public void savePictureAsync() {
//        ZRThreadTool.execute(new Runnable() {
//            Photo photo = null;
//            @Override
//            public void run() {
//                try {
//                    photo = savePicture(data);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        CaptureActivity.this.data = null;
//                        if (photo != null) {
//                            send(photo);
//                        } else
//                            Toast.makeText(CaptureActivity.this, "保存照片失败", Toast.LENGTH_SHORT).show();
//                        finish();
//                    }
//                });
//            }
//        });
    }

//    /**
//     * 保存照片
//     *
//     * @param data
//     */
//    private Photo savePicture(byte[] data) throws IOException {
//        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//        Matrix matrix = new Matrix();
//        matrix.postRotate(getRotateDegree(facing));
//        Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
//        bitmap.recycle();
//        Photo photo = new Photo();
//        photo.setWidth(rotateBitmap.getWidth());
//        photo.setHeight(rotateBitmap.getHeight());
//        photo.setFullImage(false);
//        photo.setMimetype("image/jpeg");
//
//        FileOutputStream outStream = null;
//        File dir = new File(destnationPath);
//        if (!dir.exists())
//            dir.mkdirs();
//        File file = new File(dir, createPictureName());
//        if (!file.exists())
//            file.createNewFile();
//        outStream = new FileOutputStream(file, false);
//        rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
//        try {
//            outStream.flush();
//            outStream.close();
//            rotateBitmap.recycle();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        photo.setPath(file.getAbsolutePath());
//        photo.setSize(file.length());
//        return photo;
//    }

    /**
     * 保存图片的时候，后置摄像头需要旋转90度，前置摄像头需要旋转270度
     *
     * @param cameraId
     * @return
     */
    private int getRotateDegree(int cameraId) {
        return cameraId == Camera.CameraInfo.CAMERA_FACING_BACK ? 90 : 270;
    }

    private String createPictureName() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMDD_hhmmss");
        return "IMG_" + simpleDateFormat.format(new Date()) + ".jpg";
    }

    CamcorderProfile localObject;
    private boolean prepareVideoRecorder() {
        findViewById(R.id.iv_switch).setVisibility(View.GONE);
        try {
            if (mMediaRecorder != null)
                mMediaRecorder.release();
            this.mMediaRecorder = new MediaRecorder();

            this.mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
                @Override
                public void onError(MediaRecorder mr, int what, int extra) {
                    Log.e("录视频", "错误码：" + what);
                    Urltool.log("onError" + what);
                }
            });

            camera.unlock();
            this.mMediaRecorder.setCamera(camera);
            this.mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            this.mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

            File dir = new File(destnationPath);
            if (!dir.exists())
                dir.mkdirs();
            File file = new File(dir, createVideoName());
            if (!file.exists())
                file.createNewFile();
            videoPath = file.getAbsolutePath();
            this.mMediaRecorder.setOutputFile(videoPath);
            // 设置视频保存类型

//            // 默认的配置可能会变形,但不会崩溃
            localObject = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
            this.mMediaRecorder.setProfile(localObject);
            // 以下某些手机会崩溃,还是不用自定义了
//            this.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//            this.mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//            this.mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//            // 不设置体积变小,变得模糊
//            this.mMediaRecorder.setVideoEncodingBitRate(localObject.videoBitRate / 3);
//            // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
//            this.mMediaRecorder.setVideoSize(bestSize.x, bestSize.y);
//            // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
//            this.mMediaRecorder.setVideoFrameRate(localObject.videoFrameRate);


            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(cameraId, cameraInfo);

            // 前后置摄像头有不同的算法
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                //前置摄像头是180度旋转装的,而且没有360度的说法
                mRotationRecord = (360 - mRotationRecord) % 360;
            } else {
                //后置的已经处理了90度旋转
            }




            this.mMediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
            // 控制视频输出方向
            this.mMediaRecorder.setOrientationHint(mRotationRecord);
            this.mMediaRecorder.prepare();
            this.mMediaRecorder.start();
        } catch (Exception localException) {
            (localException).printStackTrace();
            Urltool.toast("录制失败");

            return false;
        }
        return true;
    }

    private void stopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release(); // release the recorder object
            }
            mMediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopPreview();
        showDecide();
        playVideo(videoPath);
    }


    private void justStopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release(); // release the recorder object
            }
            mMediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopPreview();
    }

    private void playVideo(String path) {
        try {
            mediaplayer = new MediaPlayer();
            mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaplayer.setDataSource(this, Uri.fromFile(new File(path)));
            mediaplayer.setDisplay(surfaceView.getHolder());
            mediaplayer.setLooping(true);
            mediaplayer.prepare();
            mediaplayer.start();


            float x = localObject.videoFrameWidth;
            float y = localObject.videoFrameHeight;

            if (mRotationRecord == 0 || mRotationRecord == 180) {
                // 选择横框去播放,不会变形,因为视频的方向已经有了
                float temp = y;
                y = x;
                x = temp;
            }

            float y1 = Urltool.getWindow_width();
            float x1 = (x * y1) / y;
            surfaceView.setLayoutParams(new RelativeLayout.LayoutParams((int) y1, (int) x1));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopVideo() {
        if (mediaplayer == null || !mediaplayer.isPlaying()) {
            return;
        }
        try {
            mediaplayer.stop();
            mediaplayer.release();
            mediaplayer = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String createVideoName() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddHHmmss");
        return "V" + simpleDateFormat.format(new Date()) + ".mp4";
    }

    public class CountDownHandler extends Handler {
        RingProgress ringProgress;
        int maxDuration;
        long startTime;
        Runnable runnable;
        Timer timer;
        public final int MSG_RESET = 1;
        public final int MSG_PREOGRESS = 2;

        public CountDownHandler(RingProgress ringProgress, int maxDuration, Runnable runnable) {
            this.ringProgress = ringProgress;
            this.maxDuration = maxDuration;
            startTime = System.currentTimeMillis();
            this.ringProgress.setMax(maxDuration);
            this.runnable = runnable;


        }

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case MSG_RESET:
                    ringProgress.setProgress(0);
                    break;
                case MSG_PREOGRESS:
                    int progress = (int) (System.currentTimeMillis() - startTime);
                    if (progress > maxDuration) {
                        progress = maxDuration;
                        runnable.run();
                    }
                    ringProgress.setProgress(progress);
                    break;
            }
        }

        public void start() {
            startTime = System.currentTimeMillis();
            sendEmptyMessage(MSG_RESET);
            timer = new Timer();
            timer.schedule(new CountDownTask(this), 0, 40);
        }

        public void stop() {
            timer.cancel();
            startTime = System.currentTimeMillis();
            sendEmptyMessage(MSG_RESET);
        }

        public void updateProgress() {
            sendEmptyMessage(MSG_PREOGRESS);
        }
    }

    public class CountDownTask extends TimerTask {
        CountDownHandler countDownHandler;

        public CountDownTask(CountDownHandler countDownHandler) {
            this.countDownHandler = countDownHandler;
        }

        @Override
        public void run() {
            countDownHandler.updateProgress();
        }
    }
}
